package com.regvision.contacts.ui;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.google.gson.Gson;
import com.regvision.contacts.R;
import com.regvision.contacts.domain.ContactDataModel;
import com.regvision.contacts.domain.ContactModel;
import com.regvision.contacts.main.ContactsApplication;
import com.regvision.contacts.mode.Observable;
import com.regvision.contacts.mode.Observer;
import com.regvision.contacts.ui.adapter.ContactAdapter;
import com.regvision.contacts.utils.ContactsUtils;
import com.regvision.contacts.utils.ListViewUtils;
import com.regvision.contacts.utils.LogUtil;
import com.regvision.contacts.utils.SharedPrefUtil;
import com.regvision.contacts.utils.Util;
import com.regvision.contacts.widget.sort.CharacterParser;
import com.regvision.contacts.widget.sort.PinyinComparator;
import com.regvision.contacts.widget.sort.SideBar;
import com.regvision.contacts.widget.sort.SideBar.OnTouchingLetterChangedListener;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.SearchView.OnQueryTextListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends BaseActivity implements OnItemLongClickListener, 
													OnItemClickListener, Observer {
	
	// 所有联系人
	private List<ContactModel> mModels;
	
	// ListView中需要显示的联系人
	private List<ContactModel> mContactModels;
	private ContactAdapter mAdapter;
	private ListView mListView;
	private SideBar mSideBar;
	private TextView mDialog;
	
	private SearchView mSearchView;
	
	private TextView mTvTip;
	
	/** 汉字转换成拼音的类  */
	private CharacterParser characterParser;
	/** 根据拼音来排列ListView里面的数据类  */
	private PinyinComparator pinyinComparator;
	
	private ContactsApplication mContactsApplication;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        findView();
        initData();
        initView();
        
        startChannel();
    }
    
    private void findView() {
    	this.mTvTip = (TextView) findViewById(R.id.tv_contact_tip);
		this.mSideBar = (SideBar) findViewById(R.id.sb_contact);
		this.mListView = (ListView) findViewById(R.id.lv_contact);
		this.mDialog = (TextView) findViewById(R.id.tv_contact_dialog);
	}
    
    private void initData() {

		// 实例化汉字转拼音类
		characterParser = CharacterParser.getInstance();
		// 实例化排序类
		pinyinComparator = new PinyinComparator();
		
		mModels = ContactsUtils.getContacts(getContext());
		// 进行排序
		Collections.sort(mModels, pinyinComparator);
		
		mContactModels = new ArrayList<ContactModel>();
		mContactModels.addAll(mModels);
		
		mAdapter = new ContactAdapter(getContext(), R.layout.item_sort, mContactModels);
		
		mContactsApplication = (ContactsApplication)getApplication();
    }
    
    private void initView() {
    	
    	actionBar.setHomeButtonEnabled(false);
    	
    	mListView.setAdapter(mAdapter);
    	mListView.setOnItemClickListener(this);
    	mListView.setOnItemLongClickListener(this);
    	
    	// 判断是否有联系人
    	if (mContactModels.size() == 0) {
			mListView.setVisibility(View.GONE);
			mTvTip.setVisibility(View.VISIBLE);
			mTvTip.setText(getString(R.string.no_contact));
		}
    	
    	mSideBar.setTextView(mDialog);
		// 设置右侧触摸监听
		mSideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {
				// 该字母首次出现的位置
				int position = mAdapter.getPositionForSection(s.charAt(0));
				if (position != -1) {
					ListViewUtils.smoothScrollListView(mListView, position);
				}
			}
		});
    }
    
    @SuppressLint("DefaultLocale") 
    private void search(String str) {
    	// 清除原有数据
    	mContactModels.clear();
    	// 匹配搜索
    	if (TextUtils.isEmpty(str)) {
    		mContactModels.addAll(mModels);
    	} else {
    		// 根据拼音进行匹配
        	LogUtil.i(TAG, str);
    		String strSearch = characterParser.getSelling(str).toLowerCase();
    		for (int i = 0; i < mModels.size(); i++) {
    			if (mModels.get(i).sortLetters.toLowerCase().indexOf(strSearch) != -1) {
    				mContactModels.add(mModels.get(i));
    			}
    		}
    	}
    	if (mContactModels.size() == 0) {
			// 没有匹配的联系人
    		mListView.setVisibility(View.GONE);
    		mTvTip.setVisibility(View.VISIBLE);
    		mTvTip.setText(getString(R.string.no_search_contact));
		} else {
    		mTvTip.setVisibility(View.GONE);
    		mListView.setVisibility(View.VISIBLE);
        	// 更新列表
    		mAdapter.updateView(mContactModels);
		}
    }
    
    private OnQueryTextListener onQueryTextListener() {
		return new OnQueryTextListener() {
			
			@Override
			public boolean onQueryTextSubmit(String arg0) {
				// 点击软键盘上的Submit按钮触发事件
				hideSoftInput();;
				return false;
			}
			
			@Override
			public boolean onQueryTextChange(String arg0) {
				// 当搜索框中的文字改变时触发该事件
				search(arg0);
				return false;
			}
		};
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		
		ContactDataModel model = ContactsUtils.getContact(getContext(), ((ContactModel)parent.getItemAtPosition(position)).id, ((ContactModel)parent.getItemAtPosition(position)).name);
		
		Intent intent = new Intent(getContext(), ContactActivity.class);
		intent.putExtra(ContactActivity.INTENT_CONTACT, model);
		startActivity(intent);
		
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		mSearchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
		mSearchView.setOnQueryTextListener(onQueryTextListener());
		mSearchView.setQueryHint(getString(R.string.please_input_serach_content));
		return super.onCreateOptionsMenu(menu);
	}
	
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_about:
            	openActivity(AboutActivity.class);
                return true;
            case R.id.action_rename_nick:
            	showRenameDialog();
            	return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    private void showRenameDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("请输入新的用户名");
        View view = LayoutInflater.from(this).inflate(R.layout.dialog, null);
        builder.setView(view);
        final EditText etUserName = (EditText)view.findViewById(R.id.et_content);
        etUserName.setHint("请输入新的用户名");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
            	String newUserName = etUserName.getText().toString().trim();
                if (newUserName != null && !newUserName.equals("")) {
                	SharedPrefUtil.putString(MainActivity.this, "username", newUserName);
                	restartChannel();
                }            	
            } 
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                
            }
        });
        builder.show();
	}
    
	// 关闭键盘
	private void hideSoftInput() {
		InputMethodManager imm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
	    if (imm != null) {
	        View v = this.getCurrentFocus();
	        if (v == null) {
	            return;
	        }
	        imm.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
	        mSearchView.clearFocus();
	    }
	}
	
	private String getChannelName() {
		String uuid = Util.getDeviceUUID(this);
		String userName = SharedPrefUtil.getString(this, "username", null);
		return "regvision-"+uuid+"-"+userName;
	}
	
	private void startChannel() {
		String channel = getChannelName();
		System.out.println("channel = " + channel);
		mContactsApplication.hostSetChannelName(channel);
		mContactsApplication.hostInitChannel();
		mContactsApplication.hostStartChannel();
	}
	
	private void stopChannel() {
		mContactsApplication.hostStopChannel();
	}
	
	private void restartChannel() {
		stopChannel();
		startChannel();
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		updateList();
	}
	
	@Override
	protected void updateList() {
		// TODO Auto-generated method stub
		super.updateList();

		mModels = ContactsUtils.getContacts(getContext());
		// 进行排序
		Collections.sort(mModels, pinyinComparator);
		
		mContactModels = new ArrayList<ContactModel>();
		mContactModels.addAll(mModels);
		
		mAdapter.updateView(mModels);
	}
	
	/* (non-Javadoc)
	 * @see com.regvision.contacts.ui.BaseActivity#onDestroy()
	 */
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		mContactsApplication.hostStopChannel();
		super.onDestroy();
	}

}
